﻿#region Copyright and Licensing Notice
// Copyright (C) 2011 Steven Bosnick
// 
// This program is open source software; you can redistribute it 
// and/or modifiy it under the terms of the Eclipse Public License,
// version 1.0.
// 
// This program is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A 
// PARTICULAR PURPOSE. See the Eclipse Public License for more
// details.
// 
// You should have received a copy of the Eclipse Public License 
// along with this program; if not, you can find a copy at
// "http://www.opensource.org/licenses/eclipse-1.0.php".
#endregion
using System;
using System.Threading.Tasks;
using BitwiseOre.SharedMemory.Core.Common;

namespace BitwiseOre.SharedMemory.Core.IPCQueues
{
    [SharedFactory]
    internal sealed class ListenerQueue : IListenerQueue
    {
        private readonly ISemaphore _notEmpty;
        private readonly IGuidQueue _queue;

        public ListenerQueue(ISemaphore notEmpty, IGuidQueue queue)
        {
            _notEmpty = notEmpty;
            _queue = queue;
        }

        public Task<Guid> Dequeue(TimeSpan timeout)
        {
            Func<Guid> dequeue = () => _queue.Dequeue();

            Task<Guid> task;
            if (_queue.DecrementNonZeroPending())
            {
                task = Task.Factory.StartNew(dequeue);
            }
            else
            {
                task = _notEmpty.Wait(timeout)
                    .Then(dequeue);
            }
            return task;
        }

        public void Enqueue(Guid guid)
        {
            _queue.Enqueue(guid);
            _notEmpty.Release();
        }

        public Task WaitNotEmpty(TimeSpan timeOut)
        {
            return _notEmpty.Wait(timeOut)
                .Then(_queue.IncrementPending);
        }
    }
}